package pos.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import pos.domain.Municipio;



	
	public class JDBCMunicipioDAO implements IMunicipioDAO {
		
		private Connection conn;
		IBarrioDAO barrio;

		public JDBCMunicipioDAO() {
			barrio = new JDBCBarrioDAO();
			conn = ConnectionManager.getInstance().checkOut();
		}
		protected void finalize() {
			ConnectionManager.getInstance().checkIn(conn);
		}

	public List selectAllMunicipios() {
		
		PreparedStatement stmt = null;
		List municipios = new LinkedList();
		ResultSet result = null;
		String sql = "SELECT nombre,municipioOID FROM Municipio";

		try {

			stmt = conn.prepareStatement(sql);
			result = stmt.executeQuery();
			while (result.next()) {

				Municipio m = new Municipio();
				List barrios = (List) barrio.selectBarriosMunicipio(conn, result.getInt("municipioOID"));

				m.setNombre(result.getString("nombre"));
				m.setBarrios(barrios);
				municipios.add(m);

			}
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			this.finalize();
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
			}

		}
		return municipios;
	}
	
}
